package com.weiyin.examination.view;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.PathMeasure;
import android.graphics.RectF;
import android.graphics.Region;
import android.support.v4.content.ContextCompat;
import android.util.AttributeSet;
import android.util.TypedValue;
import android.view.MotionEvent;
import android.view.SurfaceHolder;
import android.view.SurfaceView;

import com.weiyin.examination.R;
import com.weiyin.examination.util.LogUtil;

import java.util.ArrayList;
import java.util.List;

/**
 * @author njf
 */
public class SurfaceViewTemplate extends SurfaceView implements SurfaceHolder.Callback {
    private final String TAG = SurfaceViewTemplate.class.getSimpleName();
    private SurfaceHolder mHolder;
    private Canvas mCanvas;

    private String[] mStarsWai = new String[]{
            "#C", "bD", "D", "bE", "E", "F", "#F", "bG", "G", "bA", "A", "bB", "B", "bC", "C"
    };
    private String[] mStars = new String[]{"#c", "d", "#d", "be", "e", "f", "#f", "g", "#g", "ba", "a", "#a", "bb", "b", "c"};

    private int[] locations = new int[2];
    private int cencerRadius = 100;

    public String[] getmStars() {
        return mStars;
    }

    public String[] getmStarsWai() {
        return mStarsWai;
    }

    private int defaultBackground = Color.parseColor("#e5e5e5");
    private int selectBackground = Color.parseColor("#f6a721");
    private int[] mColors;
    private int[] mColorsCenter;
    private int mItemCount = 15;

    public int getSelectBackground() {
        return selectBackground;
    }

    public int[] getmColorsCenter() {
        return mColorsCenter;
    }

    public int[] getmColors() {
        return mColors;
    }

    /**
     * 整个盘块的范围
     */
    private RectF mRange = new RectF();
    private RectF mRangeW = new RectF();


    /**
     * 整个盘块的直径
     */
    private int mRadius;
    /**
     * 绘制盘块的画笔
     */
    private Paint mArcPaint;
    private Paint mArcPaintCenter;
    /**
     */
    private Paint mArcPaintBoarder;
    /**
     * 绘制文本的画笔
     */
    private Paint mTextPaint;

    /**
     * 盘块滚动的速度
     */
    private double mSpeed = 0;
    private volatile float mStartAngle = 0;
    /**
     * 转盘的中心位置
     */
    private int mCenter;
    /**
     * padding直接以paddingLeft为准
     */
    private int mPadding;
    private Bitmap mBgBitmap = BitmapFactory.decodeResource(getResources(), R.mipmap.bg2);

    private float mTextSize = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP, 20, getResources().getDisplayMetrics());
    private float markTextSize = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP, 15, getResources().getDisplayMetrics());

    private List<Region> regions;
    private List<Region> regionsCenter;
    /**
     * start add
     */
    private Region regionCenter;
    //end add


    public SurfaceViewTemplate(Context context) {
        this(context, null);
    }

    public SurfaceViewTemplate(Context context, AttributeSet attrs) {
        super(context, attrs);

        mHolder = getHolder();
        mHolder.addCallback(this);
        // 可获得焦点
        setFocusable(true);
        setFocusableInTouchMode(true);
        // 设置常量
        setKeepScreenOn(true);
    }

    private void initColors() {
        mColors = new int[]{defaultBackground, defaultBackground, defaultBackground, defaultBackground, defaultBackground, defaultBackground
                , defaultBackground, defaultBackground, defaultBackground, defaultBackground, defaultBackground, defaultBackground, defaultBackground, defaultBackground, defaultBackground};
        mColorsCenter = new int[]{defaultBackground, defaultBackground, defaultBackground, defaultBackground, defaultBackground, defaultBackground
                , defaultBackground, defaultBackground, defaultBackground, defaultBackground, defaultBackground, defaultBackground, defaultBackground, defaultBackground, defaultBackground};
    }

    private int position = -1;

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        boolean centerIsHas = false;
        if (event.getAction() == MotionEvent.ACTION_DOWN) {
            //start add
            if (regionCenter.contains((int) (event.getX()), (int) (event.getY()))) {
                return false;
            }
            //end add
            int count = 0;
            for (Region region : regionsCenter) {
                if (region.contains((int) (event.getX()), (int) (event.getY()))) {
                    centerIsHas = true;
                    position = count;
                }
                count++;
            }
            count = 0;
            if (!centerIsHas) {
                for (Region region : regions) {
                    if (region.contains((int) (event.getX()), (int) (event.getY()))) {
                        position = count;
                    }
                    count++;
                }
            }
            if (position != -1) {
                if (centerIsHas) {
                    if (mColorsCenter[position] == selectBackground) {
                        mColorsCenter[position] = defaultBackground;
                    } else {
                        mColorsCenter[position] = selectBackground;
                    }
                } else {
                    if (mColors[position] == selectBackground) {
                        mColors[position] = defaultBackground;
                    } else {
                        mColors[position] = selectBackground;
                    }
                }
                draw();
            }
        } else if (event.getAction() == MotionEvent.ACTION_UP) {
        }
        return super.onTouchEvent(event);

    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);

        int width = Math.min(getMeasuredWidth(), getMeasuredHeight());
        mPadding = getPaddingLeft();
        // 直径
        mRadius = (width - mPadding * 2) / 3 * 2;
        LogUtil.i(TAG, "mr=" + mRadius);
        // 中心点
        mCenter = width / 4;
        setMeasuredDimension(width, width);
    }

    @Override
    public void surfaceCreated(SurfaceHolder holder) {
        // 初始化绘制盘块的画笔
        mArcPaint = new Paint();
        mArcPaint.setAntiAlias(true);
        mArcPaint.setDither(true);
        mArcPaint.setColor(Color.BLACK);
        mArcPaint.setStyle(Paint.Style.FILL_AND_STROKE);
        mArcPaintCenter = new Paint();
        mArcPaintCenter.setAntiAlias(true);
        mArcPaintCenter.setDither(true);
        mArcPaintCenter.setColor(Color.BLACK);
        mArcPaintCenter.setStyle(Paint.Style.FILL_AND_STROKE);
        mArcPaintBoarder = new Paint();
        mArcPaintBoarder.setAntiAlias(true);
        mArcPaintBoarder.setDither(true);
        mArcPaintBoarder.setColor(Color.WHITE);
        mArcPaintBoarder.setStrokeWidth(3);
        mArcPaintBoarder.setStyle(Paint.Style.STROKE);
        mTextPaint = new Paint();
        mTextPaint.setAntiAlias(true);
        mTextPaint.setDither(true);
        // 如果不给透明度ff看起来像是显示在背景底部了
        mTextPaint.setColor(ContextCompat.getColor(getContext(), R.color.ff4A));
        mTextPaint.setTextSize(mTextSize);

        // 初始化盘块绘制的范围
        mRange = new RectF(mPadding + mRadius / 4, mPadding + mRadius / 4, mPadding + mRadius + mRadius / 4, mPadding + mRadius / 4 + mRadius);
        mRangeW = new RectF(mPadding, mPadding, mPadding + mRadius / 2 * 3, mPadding + mRadius / 2 * 3);
        LogUtil.i(TAG, "mpadd=" + mPadding + " mRad=" + mRadius);
        regions = new ArrayList<>();
        regionsCenter = new ArrayList<>();
        initColors();
        draw();
    }

    @Override
    public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {

    }

    @Override
    public void surfaceDestroyed(SurfaceHolder holder) {


    }

    private void draw() {
        regions.clear();
        regionsCenter.clear();
        //获取控件在屏幕的位置
        getLocationOnScreen(locations);
        mCanvas = mHolder.lockCanvas();
        try {
            if (mCanvas != null) {
                // 绘制背景
                drawBg();
                // 绘制盘块
                float tmpAngle = mStartAngle;
                float sweepAngle = 360 / mItemCount;
                Paint paint = new Paint();
                paint.setColor(defaultBackground);
                paint.setStyle(Paint.Style.FILL);
                for (int i = 0; i < mItemCount; i++) {
                    mArcPaint.setColor(mColors[i]);
                    mArcPaintCenter.setColor(mColorsCenter[i]);
                    Path mPath = new Path();
                    mPath.moveTo(mRangeW.centerX(), mRangeW.centerY());
                    mPath.lineTo(mathX(sweepAngle), mathY(sweepAngle));
                    mPath.addArc(mRangeW, tmpAngle, sweepAngle);
                    mPath.lineTo(mRangeW.centerX(), mRangeW.centerY());
                    mPath.close();
                    mCanvas.drawPath(mPath, mArcPaint);
//                    mCanvas.drawArc(mRangeW, tmpAngle, sweepAngle, true, mArcPaint);
                    mCanvas.drawArc(mRangeW, tmpAngle, sweepAngle, true, mArcPaintBoarder);
                    Path path = new Path();
                    path.moveTo(mRange.centerX(), mRange.centerY());
                    path.lineTo(mathX(sweepAngle), mathY(sweepAngle));
                    path.addArc(mRange, tmpAngle, sweepAngle);
                    path.lineTo(mRange.centerX(), mRange.centerY());
                    path.close();
                    mCanvas.drawPath(path, mArcPaintCenter);
                    Region region = new Region();
                    Region regionCenter = new Region();
                    Region region2 = new Region();
                    Region region2Center = new Region();
                    int s = (mPadding + mRadius / 2 * 3) / 2;
                    region2.set((int) (mRangeW.centerX() - mRadius), (int) (mRangeW.centerY() - mRadius), (int) (mRangeW.centerX() + mRadius), (int) (mRangeW.centerY() + mRadius));
                    region2Center.set((int) (mRange.centerX() - s), (int) (mRange.centerY() - s), (int) (mRange.centerX() + s), (int) (mRange.centerY() + s));
                    region.setPath(mPath, region2);
                    regionCenter.setPath(path, region2Center);
                    regions.add(region);
                    regionsCenter.add(regionCenter);
//                    mCanvas.drawArc(mRange, tmpAngle, sweepAngle, true, mArcPaint);
                    mCanvas.drawArc(mRange, tmpAngle, sweepAngle, true, mArcPaintBoarder);
                    //绘制外圈文本
                    drawTextWai(tmpAngle, sweepAngle, mStarsWai[i]);
                    // 绘制文本
                    drawText(tmpAngle, sweepAngle, mStars[i]);
                    // 绘制盘块图片
                    tmpAngle += sweepAngle;
                }
                Paint pain = new Paint();
                pain.setColor(Color.WHITE);
                pain.setStyle(Paint.Style.FILL);
                mCanvas.drawCircle(mRange.centerX(), mRange.centerY(), cencerRadius, pain);
                //start add
                regionCenter = new Region();
                Region region2 = new Region();
                region2.set((int) (mRange.centerX() - cencerRadius), (int) (mRange.centerY() - cencerRadius), (int) (mRange.centerX() + cencerRadius), (int) (mRange.centerY() + cencerRadius));
                Path path = new Path();
                path.addCircle(mRange.centerX(), mRange.centerY(), cencerRadius, Path.Direction.CW);
                regionCenter.setPath(path, region2);
                //end add
                mStartAngle += mSpeed;
            }
        } finally {
            if (mCanvas != null) {
                mHolder.unlockCanvasAndPost(mCanvas);// 释放mCanvas
            }
        }
    }


    private float mathX(float ao) {
        // x1   =   x0   +   r   *   cos(ao   *   3.14   /180   )
        return (float) (mRange.centerX() + (mRadius / 2) * Math.cos(ao * 3.14 / 180));
    }

    private float mathY(float ao) {
        // y1   =   y0   +   r   *   sin(ao   *   3.14   /180   )
        return (float) (mRange.centerY() + (mRadius / 2) * Math.sin(ao * 3.14 / 180));
    }

    public void luckyStart(int index) {
        mColors[0] = Color.BLACK;
        draw();
    }

    public void luckyEnd() {
        mStartAngle = 0;
    }

    /**
     * 绘制每个盘块的文本
     *
     * @param tmpAngle
     * @param sweepAngle
     * @param mStr
     */
    private void drawTextWai(float tmpAngle, float sweepAngle, String mStr) {

        Path path = new Path();
        RectF rectF = new RectF(mRangeW.left + 50, mRangeW.top + 50, mRangeW.right - 50, mRangeW.bottom - 50);
        path.addArc(rectF, tmpAngle, sweepAngle);
        PathMeasure pathMeasure = new PathMeasure(path, false);
        float distance;
        if (tmpAngle > 140 && tmpAngle < 270) {
            distance = 40;
        } else {
            distance = 60;
        }
        LogUtil.i(TAG, "tmpAngle=" + tmpAngle + " sweepAngle=" + sweepAngle + " mStr=" + mStr);
        if (mStr.length() > 1) {
            float[] floats = new float[2];
            float[] floats1 = new float[2];
            pathMeasure.getPosTan(distance, floats, floats1);
            mCanvas.drawText(mStr.substring(1), floats[0], floats[1], mTextPaint);

            mTextPaint.setTextSize(markTextSize);
            float textWidth1 = mTextPaint.measureText(mStr.substring(0, 1));
            mCanvas.drawText(mStr.substring(0, 1), floats[0] - textWidth1, floats[1] - textWidth1, mTextPaint);
            mTextPaint.setTextSize(mTextSize);
        } else {
            float[] floats = new float[2];
            float[] floats1 = new float[2];
            pathMeasure.getPosTan(distance, floats, floats1);
            mCanvas.drawText(mStr, floats[0], floats[1], mTextPaint);
        }
    }

    void drawText(Canvas canvas, String text, float x, float y, Paint paint, float angle) {
        if (angle != 0) {
            canvas.rotate(angle, x, y);
        }
        canvas.drawText(text, x, y, paint);
        if (angle != 0) {
            canvas.rotate(-angle, x, y);
        }
    }

    /**
     * 绘制每个盘块的文本
     *
     * @param tmpAngle
     * @param sweepAngle
     * @param mStr
     */
    private void drawText(float tmpAngle, float sweepAngle, String mStr) {

        Path path = new Path();
        RectF rectF = new RectF(mRange.left + 50, mRange.top + 50, mRange.right - 50, mRange.bottom - 50);
        path.addArc(rectF, tmpAngle, sweepAngle);
        PathMeasure pathMeasure = new PathMeasure(path, false);

        float distance;
        if (tmpAngle > 160) {
            distance = 30;
        } else if (tmpAngle < 160 && tmpAngle > 110) {
            distance = 20;
        } else {
            distance = 40;
        }
//        LogUtil.i(TAG, "tmpAngle=" + tmpAngle + " sweepAngle=" + sweepAngle + " mStr=" + mStr);
        if (mStr.length() > 1) {
            float[] floats = new float[2];
            float[] floats1 = new float[2];
            pathMeasure.getPosTan(distance, floats, floats1);
            mCanvas.drawText(mStr.substring(1), floats[0], floats[1], mTextPaint);

            mTextPaint.setTextSize(markTextSize);
            float textWidth1 = mTextPaint.measureText(mStr.substring(0, 1));
            mCanvas.drawText(mStr.substring(0, 1), floats[0] - textWidth1, floats[1] - textWidth1, mTextPaint);
            mTextPaint.setTextSize(mTextSize);

        } else {
            float[] floats = new float[2];
            float[] floats1 = new float[2];
            pathMeasure.getPosTan(distance, floats, floats1);

            mCanvas.drawText(mStr, floats[0], floats[1], mTextPaint);
        }
    }

    /**
     * 绘制背景
     */
    private void drawBg() {
        mCanvas.drawColor(Color.WHITE);
//        mCanvas.drawBitmap(mBgBitmap, null, new Rect(mPadding / 2, mPadding / 2, getMeasuredWidth() - mPadding / 2, getMeasuredHeight() - mPadding / 2), null);
    }
}
